package com.tsl.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tsl.reggie.common.R;
import com.tsl.reggie.domain.po.User;
import com.tsl.reggie.service.IUserService;
import com.tsl.reggie.utils.SMSUtils;
import com.tsl.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author 唐书亮
 * @since 2024-02-27
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    RedisTemplate<Object,Object> redisTemplate;
    @PostMapping("sendMsg")
    public R<User> btnCode(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        //判断手机号是否为空
        if (!StringUtils.isEmpty(phone)){

            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode4String(6);
            //发送验证码
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            log.info("发送的code是{}",code);
            //保存验证码
            //session.setAttribute("code",code);
            redisTemplate.opsForValue().set("phone",code,5l, TimeUnit.MINUTES);
            return R.success(user);
        }

        return R.error("验证码获取失败");

    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //获取请求里Session的code
        //String currentCode = session.getAttribute("code").toString();
        String currentCode =(String) redisTemplate.opsForValue().get("phone");
        //对比code
        if (code != null&&code.equals(currentCode)) {
            //比对成功,从数据库查找手机号,如果有,为老用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            //没有,注册为新用户
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户id存入到Session
            session.setAttribute("userId", user.getId());
            //删除验证码
            redisTemplate.delete("phone");
          return R.success(user);
        }
        return R.error("登陆失败");

    }

}
